import { defineConfig } from "vite";
import vue from "@vitejs/plugin-vue";
import { resolve } from "path";

/**
 * element-plus 按需加载处理
 * 按需加载处理后，无需在引入 element-plus 相关的文件，系统会自动引入
 */
import AutoImport from "unplugin-auto-import/vite";
import Components from "unplugin-vue-components/vite";
import { ElementPlusResolver } from "unplugin-vue-components/resolvers";

import { codeInspectorPlugin } from "code-inspector-plugin";
import { createHtmlPlugin } from "vite-plugin-html";
import { execSync } from "child_process";

// 获取当前分支名称
const getGitBranch = () => {
  try {
    return execSync("git rev-parse --abbrev-ref HEAD").toString().trim();
  } catch (e) {
    return "unknown";
  }
};

// 获取当前打包时间
const getBuiltTime = () => {
  const now = new Date();
  const Y = now.getFullYear();
  const M = now.getMonth() + 1;
  const D = now.getDate();
  const h = now.getHours();
  const m = now.getMinutes();
  const s = now.getSeconds();
  return `${Y}-${M.toString().padStart(2, "0")}-${D.toString().padStart(
    2,
    "0"
  )} ${h.toString().padStart(2, "0")}:${m.toString().padStart(2, "0")}:${s
    .toString()
    .padStart(2, "0")}`;
};

// https://vite.dev/config/
export default defineConfig({
  resolve: {
    alias: {
      "@": resolve(__dirname, "src"),
    },
  },

  plugins: [
    vue(),
    AutoImport({
      resolvers: [ElementPlusResolver()],
    }),
    Components({
      resolvers: [ElementPlusResolver()],
    }),

    codeInspectorPlugin({
      bundler: "vite",
    }),
    createHtmlPlugin({
      minify: true,
      inject: {
        tags: [
          {
            injectTo: "head-prepend",
            tag: "meta",
            attrs: {
              charset: "UTF-8",
              "data-builtTime": getBuiltTime(),
              "data-branchName": getGitBranch(),
            },
          },
        ],
      },
    }),
  ],

  server: {
    port: 8080,

    proxy: {
      "/API/api": {
        target: "http://localhost:8888", // 后端服务器地址
        changeOrigin: true, // 是否改变请求源
        rewrite: (path) => path.replace(/^\/API/, ""), // 可选，重写路径
      },
    },
  },

  build: {
    rollupOptions: {
      input: "src/main.ts",
      output: {
        // 设置 CSS 文件名（不带指纹）
        assetFileNames: (assetInfo) => {
          if (assetInfo.name?.endsWith(".css")) {
            // 这里把 vendor 分包对应的 CSS 文件设置为不带指纹的文件名
            if (assetInfo.name.includes("vendor")) {
              return "assets/vendor.css"; // 不带指纹
            }

            // 默认其他 CSS 文件会加上指纹
            return "assets/[name].[hash].css";
          }

          // 其他资源（如图片等）保持默认
          return "assets/[name][extname]";
        },

        // 定义分包文件的文件名（不带指纹）
        chunkFileNames: (chunkInfo) => {
          // 如果是 vendor 分包，则不加指纹
          if (chunkInfo.name === "vendor") {
            return "assets/vendor.js"; // 不带指纹
          }

          // 如果是 vue 分包，则不加指纹
          if (chunkInfo.name === "vue") {
            return "assets/vue.js"; // 不带指纹
          }

          // 默认处理其他分包文件
          return "assets/[name].[hash].js"; // 带指纹
        },

        manualChunks(id) {
          // 基于某些条件手动拆分
          if (id.includes("node_modules/vue")) {
            return "vue"; // 把 vue 作为一个单独的 chunk
          }

          if (id.includes("node_modules")) {
            return "vendor"; // 把所有的 node_modules 依赖提取到 vendor.chunk.js
          }
        },
      },
    },
  },
});
